package com.neusoft.controller;

import com.neusoft.po.CommonResult;
import com.neusoft.po.User;
import com.neusoft.po.UserAvatar;
import com.neusoft.po.UserPsd;
import com.neusoft.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/UserController")
@RefreshScope
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private BusinessService businessService;

	@GetMapping("/getUserByIdByPass/{userId}/{password}")
    public CommonResult<User> getUserByIdByPass(
            @PathVariable("userId") String userId,
            @PathVariable("password") String password
    ){
		try {
                 User param = new User();
			     param.setUserId(userId);
			     param.setPassword(password);
			     User userByIdByPass = userService.getUserByIdByPass(param);
			if (userDTO != null) {
				session.setAttribute("userId", userDTO.getUserId());

				Business business = businessService.getBusinessByUserId(userDTO.getUserId());
				if (business != null) {
					userDTO.setBusinessId(business.getBusinessId());
				}

				// 确保返回的 userDTO 中有 userImg 属性
				if (userDTO.getUserImg() == null || userDTO.getUserImg().isEmpty()) {
					userDTO.setUserImg(""); // 保证 userImg 不为 null
				}

				// 添加 Cookie
				Cookie cookie = new Cookie("token", user.getUserId());
				cookie.setPath("/");
				response.addCookie(cookie);

				return userDTO;

			} else {
				System.out.println("UserDTO is null");
			    return new CommonResult(200, "success", userByIdByPass);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@GetMapping("/getUserById/{userId}")
    public CommonResult<Integer> getUserById(
            @PathVariable("userId") String userId
    ) throws Exception {
        User userById = userService.getUserById(userId);
        return new CommonResult(200, "success", userById);
    }

	@PostMapping("/saveUser")
	@PostMapping("/saveUser/{userId}/{password}/{userName}/{userSex}")
    public CommonResult<Integer> saveUser(
            @PathVariable("userId") String userId,
            @PathVariable("password") String password,
            @PathVariable("userName") String userName,
            @PathVariable("userSex") Integer userSex
    ) {
		try {
			User user = new User();
	        user.setUserId(userId);
	        user.setPassword(password);
	        user.setUserName(userName);
	        user.setUserSex(userSex);
	        int result = userService.saveUser(user);
			if (result > 0) {
				Cookie cookie = new Cookie("token", user.getUserId());
				cookie.setPath("/");
				response.addCookie(cookie);
			}
			return new CommonResult(200, "success", result);
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}


}